package org.cfx.auth.service.impl;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.cfx.auth.domain.dto.LoginDto;
import org.cfx.auth.service.ILoginService;
import org.cfx.basic.myenum.LoginContext;
import org.cfx.basic.service.impl.TokenService;
import org.cfx.basic.util.RedisUtil;
import org.cfx.org.domain.Employee;
import org.cfx.org.domain.dto.EmployeeDto;
import org.cfx.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author RTX 9090
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${token.key}")
    private String tokenKey;

    @Override
    public Map<String, Object> login(LoginDto loginDto) throws Exception {
        if (loginDto.getUsername()==null || loginDto.getUsername().length()<1) throw new Exception("用户名不能为空！");
        if (loginDto.getPassword()==null || loginDto.getPassword().length()<1) throw new Exception("用户名不能为空！");
        Employee loginEmployee = employeeMapper.login(loginDto.getUsername());
        if (loginEmployee==null) throw new Exception("用户名或密码错误！");
        if (!loginEmployee.getPassword().equals(loginDto.getPassword())) throw new Exception("用户名或密码错误！");

        //用户返回用户信息给前端
        Map<String, Object> hashMap = new HashMap<>();

        hashMap.put(loginDto.getUsername(),loginEmployee);

        // 生成token
        String token = JWTUtil.createToken(hashMap,tokenKey.getBytes());

        //全局只存在一个
        Map<String, Employee> map = LoginContext.CONTEXT.getMap();
        map.put(token,loginEmployee);

        //用户返回用户信息+token给前端
        loginEmployee.setPassword("");
        loginEmployee.setEmail("");
        Map<String, Object> loginMap = new HashMap<>();
        loginMap.put("user",loginEmployee);
        loginMap.put("token",token);


        return loginMap;
    }

    @Override
    public EmployeeDto login2(LoginDto loginDto, HttpServletRequest request) throws Exception {
        EmployeeDto dto = new EmployeeDto();
        if (StringUtils.isBlank(loginDto.getUsername()) || loginDto.getUsername().length()<1) throw new Exception("用户名不能为空！");
        if (StringUtils.isBlank(loginDto.getPassword()) || loginDto.getPassword().length()<1) throw new Exception("用户名不能为空！");
        Employee user = employeeMapper.login2(loginDto);
        if (user==null) throw new Exception("用户名或密码错误！");
        if (user.getPassword().equals(loginDto.getPassword())) {//成功
//            if (redisUtil.getKeyByName(user.getUsername())) throw new Exception("用户已存在！请先退出登录！");
            String userAgentStr = request.getHeader("user-agent");
            //生成token
            String token = this.tokenService.generateToken(userAgentStr, loginDto.getUsername(),user);
            //组织前台需要的信息
            dto.setToken(token);
            dto.setIsLogin(true);
            dto.setTokenCreatedDate(System.currentTimeMillis());
            dto.setTokenExpiryDate(System.currentTimeMillis() + 7200000);
            user.setPassword("");
            user.setEmail("");
            dto.setUser(user);
            //保存token
            synchronized (LoginServiceImpl.class) {
                this.tokenService.save(token, dto);
//                this.tokenService.saveUser(user.getUsername(),dto,token);
            }
        }else {//失败
            dto.setIsLogin(false);
        }
        return dto;

    }
}
